import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/match/detail/lq_match_detail_logic.dart';
import 'package:ball_lion/server/api/basketball_api.dart';
import 'package:ball_lion/entity/match/zq_odds_entity.dart';
import 'match_odds_logic.dart';

class LqOddsDetailLogic extends MatchOddsLogic {
  late final detail = Get.find<LqMatchDetailLogic>(tag: '${Get.arguments[1]}');
  List<String> typeList = ["胜负", "让分", "大小分"];
  late final TabController tabController = TabController(
      length: typeList.length,
      vsync: this,
      initialIndex: Get.arguments[2] ?? 0);
  final List<int> _numList = [2001, 2002, 2003];
  List<List<String>> headTypeList = [
    ["客", "主"],
    ["客", "让", "主"],
    ["大", "盘", "小"]
  ];
  int _typeIndex = Get.arguments[2] ?? 0;
  late final List<int> _selectIndex =
      List.generate(_numList.length, (index) => 0);
  bool isLoading = true;
  late final List<List<SoccerOddsCompanyEntity>> _companies =
      List.generate(_numList.length, (index) => []);
  late final List<List<SoccerOddsDetailEntity>> _data =
      List.generate(_numList.length, (index) => []);

  List<List<SoccerOddsDetailEntity>> get data => _data;

  List<List<SoccerOddsCompanyEntity>> get companies => _companies;
  List<int> get numList => _numList;
  int get typeIndex => _typeIndex;
  List<int> get selectIndex => _selectIndex;

  @override
  void onInit() {
    tabController.addListener(() {
      typeIndex = tabController.index;
    });
    super.onInit();
  }

  void setSelectIndex(int index, int value) {
    if (value < 0) {
      _selectIndex[index] = 0;
    } else {
      _selectIndex[index] = value;
    }
    update();
  }

  set typeIndex(int value) {
    _typeIndex = value;
    update();
  }

  @override
  void onReady() async {
    typeIndex = Get.arguments[2];
    await requestCompany();
    for (var i = 0; i < _numList.length; i++) {
      await requestData(_selectIndex[i], index: i);
    }
    isLoading = false;
    update();
  }

  Future requestData(int i, {int? index}) async {
    try {
      _data[index ?? _typeIndex] = await BasketballApi.getLqMatchOddsDetail(
              detail.matchId,
              _companies[index ?? _typeIndex][i].id == -1 ||
                      _companies[index ?? _typeIndex][i].id == null
                  ? 0
                  : _companies[index ?? _typeIndex][i].id!,
              _numList[index ?? _typeIndex],
              _companies[index ?? _typeIndex][i].line ?? "") ??
          [];
    } catch (e) {
      _data[_typeIndex] = [];
    }
    update();
  }

  Future requestCompany() async {
    for (var i = 0; i < _numList.length; i++) {
      _companies[i] = await BasketballApi.getLqMatchOddsCompany(
              detail.matchId, _numList[i]) ??
          [];
      setSelectIndex(
          i,
          _companies[i]
              .indexWhere((element) => element.id == Get.arguments[0]));
    }
    update();
  }
}
